﻿using System;
using System.Configuration;
using System.Net;
using System.Security.Permissions;
using DMS.NAVWebService;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using System.IO;

namespace DMS.DocumentStoreUpdater
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class DocumentStoreUpdater : SPItemEventReceiver
    {

       public override void ItemAdded(SPItemEventProperties properties)
       {
           base.ItemAdded(properties);
           SPListItem item = properties.ListItem;
           item["Title"] = item["LinkFilename"];

           this.EventFiringEnabled = false;
           item.UpdateOverwriteVersion();
           this.EventFiringEnabled = true;
       }

       /// <summary>
       /// An item is being updated.
       /// </summary>
       public override void ItemUpdating(SPItemEventProperties properties)
       {
           base.ItemUpdating(properties);
           SPListItem item = properties.ListItem;
           //string docType = item["DocumentType"].ToString();
           string docType = properties.AfterProperties["DocumentType"].ToString();

           try
           {
               if (docType == "GAT" || docType == "Credit Applications")
               {

                   SPFile sourceFile = properties.ListItem.File;
                   SPFile destFile;


                   using (Stream stream = sourceFile.OpenBinaryStream())
                   {
                       SPDocumentLibrary destLibrary;
                       if (docType == "GAT")
                       {
                           destLibrary = (SPDocumentLibrary)properties.ListItem.Web.Webs["GATs"].Lists["GATs"];
                       }
                       else
                       {
                           destLibrary = (SPDocumentLibrary)properties.ListItem.Web.Webs["CreditApplications"].Lists["CreditApplications"];
                       }
                       string fileName = properties.AfterProperties["vti_title"].ToString();
                       destFile = destLibrary.RootFolder.Files.Add(fileName, stream);
                       stream.Close();
                   }

                   SPListItem destItem = destFile.Item;
                   SPListItem sourceItem = sourceFile.Item;
                   destItem["Title"] = properties.AfterProperties["vti_title"].ToString();
                   //destItem["DocumentType"] = sourceItem["DocumentType"];
                   destItem["DocumentType"] = properties.AfterProperties["DocumentType"];

                   //destItem["DocumentDate"] = sourceItem["DocumentDate"];
                   destItem["DocumentDate"] = properties.AfterProperties["DocumentDate"];
                   //destItem["CustomerName"] = sourceItem["CustomerName"];
                   destItem["CustomerName"] = properties.AfterProperties["CustomerName"];
                   //string customerNo = sourceItem["CustomerNumber"].ToString();
                   string customerNo = properties.AfterProperties["CustomerNumber"].ToString();
                   destItem["CustomerNumber"] = customerNo;
                   this.EventFiringEnabled = false;
                   destItem.UpdateOverwriteVersion();
                   this.EventFiringEnabled = true;

                   bool success = UpdateNAV(docType, customerNo, destFile.Web.Url + "/" + destFile.Url);
                   if (!success)
                   {
                       properties.Cancel = true;
                       properties.ErrorMessage = "Update NAV for this Document failed. Please contact site administrator. ";
                       properties.Status = SPEventReceiverStatus.CancelWithError;
                   }

               }
           }
           catch (Exception ex)
           {
               properties.Cancel = true;
               properties.ErrorMessage = "Error occurs on moving Files : " + ex.Message;
               properties.Status = SPEventReceiverStatus.CancelWithError;
           }
           
       }

       public override void ItemUpdated(SPItemEventProperties properties)
       {
           base.ItemUpdated(properties);
           //bool exported = Convert.ToBoolean(properties.ListItem["Exported"].ToString());
           //if(exported)
           //{
           //    int id = properties.ListItemId;
           //    SPList list = properties.List;
           //    this.EventFiringEnabled = false;
           //    list.Items.DeleteItemById(id);
           //    this.EventFiringEnabled = true;
           //}
       }

        private bool UpdateNAV(string docType, string customerNo, string url)
        {
            SharepointImport ws = new SharepointImport();

            string username = ConfigurationManager.AppSettings["NAVWSUsername"];
            string password = ConfigurationManager.AppSettings["NAVWSPassword"];
            string domain = ConfigurationManager.AppSettings["NAVWSDomain"];
            string wsUrl = ConfigurationManager.AppSettings["NAVWSUrl"];

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(domain) || string.IsNullOrEmpty(wsUrl))
                return false;

            ws.Credentials = new NetworkCredential(username,password,domain);

            string type = docType.Equals("GAT", StringComparison.CurrentCultureIgnoreCase) ? "GAT" : "CREDAPP";
            ws.Url = wsUrl;
            bool success = ws.LoadAccountURLs(type, customerNo, url);
            return success;
        }
    }
}
